/*
 *  Copyright 2011 yura.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *  under the License.
 */

package org.opu.vcforms.view.component.db;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import javax.swing.AbstractAction;
import javax.swing.Box;
import javax.swing.Icon;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.JToggleButton;
import org.opu.vcforms.datasource.UserData;
import org.opu.vcforms.datasource.UserData.JDBCProperties;
import org.opu.vcforms.resource.ResourceHandle;
import org.opu.vcforms.view.View;
import org.opu.vcforms.view.ViewHandler;
import org.opu.vcforms.view.component.GUIProperties;

/**
 *
 * @author yura
 */
public class UserDataPane extends JPanel implements View{

    private UserData data;
    private UserDataPaneI18n i18n;

    private JTextField user;
    private JTextField passwordTf;
    private JPasswordField passwordPf;

    private JTextField dbName;
    private JTextField dbHost;
    private JTextField dbPort;

    private JComboBox dbProperties;

    private JToggleButton showPswdBtn;
    private JCheckBox savePswd;

    private JComponent southPane;

    public UserDataPane() {
        this(null);
    }

    public UserDataPane(UserData data) {
        this(data, new DefaultUserDataPaneI18n());
    }

    public UserDataPane(UserData data, UserDataPaneI18n i18n) {
        super(new BorderLayout());//new GridLayout(7, 2, 3, 3));

        if (data == null){
            JDBCProperties jdbc = null;
            try {
                jdbc = UserData.AVAILABLE_JDB.iterator().next().newInstance();
            } catch (Exception ex) {//It`s imposible...
            }
            data = new UserData("", "", "", "localhost", jdbc);
        }

        this.data = data;
        this.i18n = i18n;
        initVar();
        initComponent();
    }

    @Override
    public void reinit() {
        removeAll();
        this.initComponent();
    }

    @Override
    public void resetData() {
    }

    JComponent getSouthPane() {
        return southPane;
    }

    private void initComponent() {
        JPanel pane = new JPanel(new GridLayout(6, 2, 5, 1));

        JComponent pswdPane = Box.createHorizontalBox();//new JPanel();
        pswdPane.add(passwordPf);
        pswdPane.add(passwordTf);
        pswdPane.add(showPswdBtn);

        southPane.add(savePswd);

        pane.add(new JLabel(i18n.getDbClass(), JLabel.RIGHT));
        pane.add(getCompInBox(getCompInBox(dbProperties)));

        pane.add(new JLabel(i18n.getUserName(), JLabel.RIGHT));
        pane.add(getCompInBox(user));
        pane.add(new JLabel(i18n.getUserPassword(), JLabel.RIGHT));
        pane.add(pswdPane);

        pane.add(new JLabel(i18n.getDbHost(), JLabel.RIGHT));
        pane.add(getCompInBox(dbHost));
        pane.add(new JLabel(i18n.getDbName(), JLabel.RIGHT));
        pane.add(getCompInBox(dbName));
        pane.add(new JLabel(i18n.getDbPort(), JLabel.RIGHT));
        pane.add(getCompInBox(dbPort));

        add(ViewHandler.getCompInStrut(pane), BorderLayout.CENTER);
        add(ViewHandler.getCompInStrut(southPane), BorderLayout.SOUTH);
    }

    private void initVar() {
        southPane = Box.createHorizontalBox();
        user = new JTextField(data.getUser());
        passwordPf = new JPasswordField(data.getPassword());
        passwordTf = new JTextField(passwordPf.getDocument(), null, 0);
        dbName = new JTextField(data.getDbName());
        dbHost = new JTextField(data.getDbHost());
        dbPort = new JTextField(data.getDbPort());
        try {
            dbProperties = new JComboBox(instances(UserData.AVAILABLE_JDB));
        } catch (Exception ex) {
        }
        
        showPswdBtn = new JToggleButton(new ShowPswdBtnAction());
        savePswd = new JCheckBox(i18n.getGUISavePswdText());

        passwordTf.setVisible(false);

        dbProperties.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JComboBox box = (JComboBox) e.getSource();
                JDBCProperties source = (JDBCProperties) box.getSelectedItem();
                dbPort.setText(source.getDefaultPort());
            }
        });
        dbProperties.setSelectedItem(data.getDbProperties());
    
        setSize(user);
        setSize(passwordPf);
        setSize(passwordTf);
        setSize(dbName);
        setSize(dbHost);
        setSize(dbPort);
        setSize(dbProperties);
    }

    public UserData getData() {
        data.setUser(user.getText());
        data.setPassword(passwordTf.getText());
        data.setDbHost(dbHost.getText());
        data.setDbName(dbName.getText());
        data.setDbPort(dbPort.getText());
        data.setDbProperties((JDBCProperties) dbProperties.getSelectedItem());
        return data;
    }

    public boolean isSavePasswordSelected(){
        return savePswd.isSelected();
    }

    JDBCProperties[] instances(Collection<Class<? extends JDBCProperties>> classes)
            throws InstantiationException, IllegalAccessException{
        
        ArrayList<JDBCProperties> ret = new ArrayList<JDBCProperties>(classes.size());
        Iterator<Class<? extends JDBCProperties>> iterator = classes.iterator();

        while(iterator.hasNext()){
            ret.add((JDBCProperties) iterator.next().newInstance());
        }

        return ret.toArray(new JDBCProperties[ret.size()]);
    }

    Dimension setSize(JComponent comp){
        Dimension ps = comp.getPreferredSize();
        ps.width = comp.getMaximumSize().width;
        comp.setMaximumSize(ps);
        return ps;
    }

    JComponent getCompInBox(JComponent comp){
        Box box = Box.createHorizontalBox();
        box.add(comp);
        return box;
    }

    public void addApproveAction(ActionListener action){
        user.addActionListener(action);
        passwordTf.addActionListener(action);
        passwordPf.addActionListener(action);
        dbName.addActionListener(action);
        dbHost.addActionListener(action);
        dbPort.addActionListener(action);
        dbProperties.addActionListener(action);
    }
    

    class ShowPswdBtnAction extends AbstractAction {
        static final String name = "showPswdBtn";

        public ShowPswdBtnAction() {
            this(i18n.getGUIShowPswdBtnText(),
                    ResourceHandle.getIcon(name + ".png",
                    GUIProperties.instance().pane.button.getIconType()),
                    i18n.getGUIShowPswdBtnTooltipe());
        }

        public ShowPswdBtnAction(String name, Icon icon, String description) {
            super(name, icon);
            putValue(SHORT_DESCRIPTION, description);
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            if (e.getSource() instanceof JToggleButton){
                JToggleButton button = (JToggleButton) e.getSource();
                if (button.isSelected()){
                    passwordPf.setVisible(false);
                    passwordTf.setVisible(true);
                } else {
                    passwordPf.setVisible(true);
                    passwordTf.setVisible(false);
                }
                ((JComponent)passwordPf.getParent()).revalidate();
            }
        }
    }

}
